import userStore from '@/store/modules/user'
var configs = {},
	roles = null;


export function amisDataChange(res) {
	if (!roles) {
		roles = userStore().roles
	}
	try {
		const businessIndex = res.config.url.indexOf('openform/tableView/getInfoByKey/'),
			formIndex1 = res.config.url.indexOf('openform/formDef/formDef/getJson/key'),
			formIndex2 = res.config.url.indexOf('openform/formDef/formDef/getControlByFormKeyAndBusinessId/');

		if (businessIndex > -1) {
			//业务
			const configKey = res.config.url.substring(businessIndex + 32, res.config.url.length).replace('?_replace=1',
					''),
				json = JSON.parse(res.data.data.json);
			let schemaJson = JSON.parse(res.data.data.schemaJson);
			setConfig(json, configKey)


			schemaJson = schemaButtonAuthFilter(schemaJson, configKey)
			schemaJson = schemaCrudAuthFilter(schemaJson, configKey)
			schemaJson = schemaFormAuthFilter(schemaJson, configKey)
			res.data.data.schemaJson = JSON.stringify(schemaJson)
		} else if (formIndex1 > -1 || formIndex2 > -1) {
			//表单
			let configKey = ''
			if (formIndex1 > -1) {
				configKey = res.config.url.substring(formIndex1 + 37, res.config.url.lastIndexOf('_AddEdit?_replace=1'))
			} else {
				configKey = res.config.url.substring(formIndex2 + 58, res.config.url.lastIndexOf('/')).replace(
					'?_replace=1', '')
			}
			res.data.data = schemaButtonAuthFilter(res.data.data, configKey)
			res.data.data = schemaCrudAuthFilter(res.data.data, configKey)
			res.data.data = schemaFormAuthFilter(res.data.data, configKey)
		}
	} catch (e) {}

	if (res.data.total != undefined) {
		res.data.data = {
			count: res.data.total,
			rows: res.data.rows || res.data.data
		}
	} else if (res.data.data === undefined && res.data.rows) {
		res.data.data = res.data.rows || []
	}
	res.data.status = 0

	return res
}

//保存业务配置
export function setConfig(config, configKey) {
	config.columnStatus = {} //字段状态
	config.columnShowAuths = {} //字段显示权限
	config.columnEditAuths = {} //字段编辑权限
	config.list.forEach(item => {
		if (!item.showRole) {
			item.showRole = []
		}
		if (!item.editRole) {
			item.editRole = []
		}
		item.showRole = item.showRole.concat(item.editRole) //有编辑权限就有显示权限
		config.columnStatus[item.columnName] = item.authFlag
		config.columnShowAuths[item.columnName] = item.showRole
		config.columnEditAuths[item.columnName] = item.editRole
	})
	configs[configKey] = config
}

//按钮权限过滤
export function schemaButtonAuthFilter(schema, configKey) {
	if (schema && schema instanceof Object) {
		const {
			action
		} = configs[configKey]
		if (['button', "export-excel"].indexOf(schema.type) > -1) {
			if (schema.id && schema.id.indexOf('__') > 0) {
				const key = schema.id.substring(0, schema.id.indexOf('__'))
				if (action[key + 'Role']) {
					const show = action[key + 'Role'].some(ite => {
						return roles.indexOf(ite) > -1
					})
					if (!show) {
						schema.hidden = true
					}
				}
			}
		} else {
			Object.keys(schema).forEach(key => {
				schema[key] = schemaButtonAuthFilter(schema[key], configKey)
			})
		}
	}
	return schema
}


//crud权限过滤
export function schemaCrudAuthFilter(schema, configKey) {
	if (schema && schema instanceof Object) {
		if (schema.type == 'crud') {
			const {
				columnStatus,
				columnShowAuths,
				columnEditAuths,
				basic,
				action
			} = configs[configKey]
			const columns = schema.columns.map((item, index) => {
				if (columnShowAuths[item.name]) {
					const show = columnShowAuths[item.name].some(ite => {
						return roles.indexOf(ite) > -1
					})
					if (!show) {
						item.hidden = true
						delete item.searchable
					}
				}
				return item
			})
			schema.columns = columns
		} else {
			Object.keys(schema).forEach(key => {
				schema[key] = schemaCrudAuthFilter(schema[key], configKey)
			})
		}
	}
	return schema
}

//form权限过滤
export function schemaFormAuthFilter(schema, configKey) {
	if (schema && schema instanceof Object) {
		if (schema.type == 'form') {
			const {
				columnStatus,
				columnShowAuths,
				columnEditAuths,
				basic,
				action
			} = configs[configKey]
			if (schema.name && schema.body) {
				const body = schema.body.map(item => {

					// if (!item.placeholder) {
					// 	if (item.type == 'input-date' || item.type.indexOf('select') > -1) {
					// 		item.placeholder = '请选择'
					// 	} else {
					// 		item.placeholder = '请输入'
					// 	}
					// }

					const col = schema.name + '__' + item.name
					if (["2", "3"].indexOf(columnStatus[col]) > -1) {
						if (columnShowAuths[col]) {
							const show = columnShowAuths[col].some(ite => {
								return roles.indexOf(ite) > -1
							})
							if (show) {
								if (columnStatus[col] == '2') {
									item.disabled = true
								} else {
									item.disabled = !columnEditAuths[col].some(ite => {
										return roles.indexOf(ite) > -1
									})
								}
							} else {
								item.hidden = true
							}
						}
					} else {
						item.hidden = true
					}
					return item
				})
				schema.body = body
				if (!body.length) {
					schema.style = {
						display: 'none'
					}
				}
			}
			if (basic.viewType == '2') {
				const isStatic = !action.addRole.some(ite => {
					return roles.indexOf(ite) > -1
				})
				if (isStatic) {
					schema = JSON.parse(JSON.stringify(schema).replace(/\$\{isStatic\}/g, '\$\{1==1\}').replace(
						/\$\{!isStatic\}/g, '\$\{1!=1\}'))
				}
			}
		} else {
			Object.keys(schema).forEach(key => {
				schema[key] = schemaFormAuthFilter(schema[key], configKey)
			})
		}
	}
	return schema
}




//获取生成器条件组合字段
export function getConditionsFields(list, showFormDefKey) {
	let fields = []
	list.forEach(item => {
		let columnJson = JSON.parse(item.columnJson);
		if (columnJson.type == 'tree-select') {
			columnJson.type = 'select'
		}
		let field = {
			"label": item.columnTitle + (showFormDefKey && item.formDefKey ? `(${item.formDefKey})` : ''),
			"type": columnJson.type.replace('input-', '').replace('area', ''),
			"name": item.columnName,
		};
		if (columnJson.type.indexOf('input-') > -1) {
			field.operators = ['equal', 'not_equal', 'is_empty', 'is_not_empty', 'like', 'not_like',
				'starts_with', 'ends_with', 'select_any_in'
			]
		}
		if (['select'].indexOf(columnJson.type) > -1) {
			field.type = 'select'
			field.searchable = true
			if (columnJson.source) {
				field.source = columnJson.source
				field.source.adaptor = `payload=payload.map(item => {item.value=item.${columnJson.valueField};
                               item.label=item.${columnJson.labelField};return item});return payload`
			}
			if (columnJson.options) {
				field.options = columnJson.options.map(item => {
					item.value = item[columnJson.valueField]
					item.label = item[columnJson.labelField]
					return item
				})
			}
		}


		if (columnJson.type == 'input-date-range') {
			field.type = 'text'
		}
		fields.push(field)
	})
	return fields
}

